import { CoolController, BaseController } from '@cool-midway/core';
import { GoodsPromoMtEntity } from '../../entity/promo_mt';
import { GoodsPromoMtService } from '../../service/promo_mt.service';
import { Body, Inject, Post } from '@midwayjs/core';
import { GoodsPromoSyncService } from '../../service/promo_sync.service';

/**
 * 促销汇总管理
 */
@CoolController({
  api: ['page', 'info'],
  entity: GoodsPromoMtEntity,
  service: GoodsPromoMtService,
  pageQueryOp: {
    keyWordLikeFields: ['a.promName', 'a.billCode'],
    fieldEq: ['a.status', 'a.promType', 'a.billState'],
    addOrderBy: {
      createTime: 'desc',
    },
    where: ctx => {
      const { startDate, endDate } = ctx.request.body;
      const conditions = [];

      // 时间范围查询
      if (startDate) {
        conditions.push(['a.startTime >= :startDate', { startDate }]);
      }
      if (endDate) {
        conditions.push(['a.endTime <= :endDate', { endDate }]);
      }

      return conditions;
    },
  },
})
export class AdminGoodsPromoMtController extends BaseController {
  @Inject()
  goodsPromoMtService: GoodsPromoMtService;

  @Inject()
  goodsPromoSyncService: GoodsPromoSyncService;

  @Post('/getByPromType')
  async getByPromType(@Body() params: { promType?: string; status?: number }) {
    return this.ok(await this.goodsPromoMtService.getByPromType(params.promType, params.status));
  }

  @Post('/getActivePromos')
  async getActivePromos() {
    return this.ok(await this.goodsPromoMtService.getActivePromos());
  }

  @Post('/syncPromoData')
  async syncPromoData() {
    const taskId = `adminSync_${Date.now()}`;
    // 异步执行同步任务
    this.goodsPromoSyncService.syncAllPromoData(taskId).catch(error => {
      console.error('促销同步任务执行失败:', error);
    });
    return this.ok({ message: '促销同步任务已启动', taskId });
  }

  @Post('/getComboDetailsByType')
  async getComboDetailsByType(@Body() params: { promType?: string }) {
    return this.ok(await this.goodsPromoMtService.getComboDetailsByType(params.promType));
  }

  @Post('/getCombosByGoodsId')
  async getCombosByGoodsId(@Body() params: { goodsId: string }) {
    return this.ok(await this.goodsPromoMtService.getCombosByGoodsId(params.goodsId));
  }
} 